package com.fine.hair.manage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fine.hair.comm.dto.AddReservationBatchDto;
import com.fine.hair.comm.dto.AddReservationBatchList;
import com.fine.hair.comm.dto.AutoAddReservationBatchDto;
import com.fine.hair.comm.enums.OrderStatus;
import com.fine.hair.comm.exception.BusinessException;
import com.fine.hair.comm.model.Item;
import com.fine.hair.comm.model.Order;
import com.fine.hair.comm.model.SysConfig;
import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.utils.Utils;
import com.fine.hair.manage.mapper.ItemMapper;
import com.fine.hair.manage.mapper.OrderMapper;
import com.fine.hair.manage.mapper.SysConfigMapper;
import com.fine.hair.manage.service.OrderService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>${Description}</p>
 *
 * @author mouseyCat
 * @date 2020/10/4 15:12
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private Snowflake snowflake;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Resource
    private ItemMapper itemMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse addReservationBatch(AddReservationBatchDto dto) {
        SysConfig sysConfig = sysConfigMapper.selectOne(new LambdaQueryWrapper<>());
        int day;
        if (dto.getMode() == 1) {
            day = sysConfig.getConfigFirst();
        }
        else if (dto.getMode() == 2) {
            day = sysConfig.getConfigSecond();
        }
        else if (dto.getMode() == 3) {
            day = sysConfig.getConfigThird();
        }
         else if (dto.getMode() == 4) {
            day = sysConfig.getConfigFourth();
        }
         else if (dto.getMode() == 0) {
             // 用户自己定时间
             day = 0;
        } else {
             throw new BusinessException("未知配置，请重新选择配置");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<AddReservationBatchList> orderList = dto.getOrderList();
        List<Date> dateList = null;
        try {
            dateList = Utils.getExecuteDateByDate(orderList.size(), day, df.parse(dto.getStartTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<Order> list = Lists.newArrayList();
        for (int i = 0; i < orderList.size(); i++) {
            orderList.get(i).setOrderId(snowflake.nextIdStr());
            orderList.get(i).setUserId(dto.getUserId());
            if (day != 0) {
                orderList.get(i).setExecuteTime(dateList.get(i));
            }
            orderList.get(i).setItemId(dto.getItemId());
            orderList.get(i).setTechnicianId(dto.getTechnicianId());
        }

        for (AddReservationBatchList pojo : orderList) {
            Item item = itemMapper.selectById(pojo.getItemId());
            Order build = Order.builder().id(pojo.getOrderId()).userId(dto.getUserId())
                    .branchId(dto.getBranchId()).technicianId(dto.getTechnicianId())
                    .itemId(dto.getItemId()).executeTime(pojo.getExecuteTime())
                    .remark(pojo.getRemark()).itemImage(item.getImage())
                    .itemTime(item.getTime()).itemTitle(item.getTitle())
                    .itemContent(item.getContent()).itemType(item.getType().toString())
                    .build();
            list.add(build);
        }
        this.saveBatch(list);
        return ApiResponse.ofSuccess();
    }

    @Override
    public ApiResponse autoAddReservationBatch(AutoAddReservationBatchDto dto) {
        int day = dto.getCycle();
        // 计算一个时间数里有多少个间隔
        int orderSize = dto.getDate() / day;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Date> dateList;
        try {
            dateList = Utils.getExecuteDateByDate(orderSize, day, df.parse(dto.getStartTime()));
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BusinessException("执行时间异常");
        }
        Item item = itemMapper.selectById(dto.getItemId());
        if (ObjectUtil.isNull(item)) {
            throw new BusinessException("当前项目不存在");
        }
        List<Order> list = Lists.newArrayList();
        for (Date date : dateList) {
            Order order = new Order();
            order.setId(snowflake.nextIdStr());
            order.setOrderStatus(OrderStatus.WILL_COMPLETE.getCode().toString());
            order.setBranchId(dto.getBranchId());
            order.setTechnicianId(dto.getTechnicianId());
            order.setExecuteTime(date);
            order.setUserId(dto.getUserId());
            order.setItemType(item.getType().toString());
            order.setItemTime(item.getTime());
            order.setItemContent(item.getContent());
            order.setItemId(item.getId().toString());
            order.setItemImage(item.getImage());
            order.setItemPrice(item.getPrice());
            order.setItemTitle(item.getTitle());
            list.add(order);
        }

        this.saveBatch(list);
        return ApiResponse.ofSuccess();
    }

    public static void main(String[] args) {

        List<Date> dateList = Utils.getExecuteDateByDate(10, 2, new Date());
        for (Date date : dateList) {
            System.out.println(DateUtil.formatDateTime(date));
        }
    }
}



